package com.ruoyi.station.controller;

import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.station.domain.*;
import com.ruoyi.station.service.SDeviceAddPropertiesService;
import com.ruoyi.station.service.SDevicePropertiesService;
import com.ruoyi.station.service.SEquipmentService;
import com.ruoyi.station.service.SMachineCabinetService;
import com.ruoyi.station.util.ParseSql;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * 设备Controller
 *
 * @author ruoyi
 * @date 2021-08-06
 */
@RestController
@RequestMapping("/equipment")
@Api(value="设备对象操作资源", tags = "设备对象操作资源")
public class SEquipmentController extends BaseController
{
    @Autowired
    private SEquipmentService sEquipmentService;

    @Autowired
    private SDeviceAddPropertiesService deviceAddPropertiesService;

    @Autowired
    private SDevicePropertiesService sDevicePropertiesService;

    @Autowired
    private SMachineCabinetService sMachineCabinetService;
    @Autowired
    private ISysUserService iSysUserService;
    /**
     * 查询设备列表
     */
    @PreAuthorize("@ss.hasPermi('system:equipment:list')")
    @PostMapping("/list")
    @ApiOperation(value="查询设备列表", notes="查询设备列表")
    public TableDataInfo query(@ApiParam @RequestBody Map map)
    {
        JSONArray queryData = JSONUtil.parseArray(map.get("queryData"));
        Integer pageNum = (Integer) map.get("pageNum");
        Integer pageSize = (Integer) map.get("pageSize");
        startPage(pageNum , pageSize);
        List<String> userList = iSysUserService.selectUserByDept(SecurityUtils.getLoginUser().getUser().getDeptId());
        QueryWrapper<SEquipment> wrapper = new QueryWrapper<>();
        Page s = new Page<>(pageNum,pageSize);
        Page<SEquipment> list = sEquipmentService.page(s,ParseSql.parse(wrapper, JSONUtil.toList(queryData, QueryData.class),userList));
        return getTableDataInfo(list.getRecords(),list.getTotal());
    }

    /**
     * 查询设备列表
     */
    @PreAuthorize("@ss.hasPermi('system:equipment:editQuery')")
    @GetMapping("/editQuery")
    @ApiOperation(value="查询设备列表", notes="查询设备列表")
    public AjaxResult editQuery(@ApiParam String equipmentIdKey ,String equipmentType)
    {
        Map result = new HashMap();
        //基础属性
        SEquipment one = sEquipmentService.getOne(new LambdaQueryWrapper<SEquipment>().eq(SEquipment::getEquipmentId , equipmentIdKey));
        result.put("sEquipment",one);
        //附加属性结构
        List<SDeviceProperties> list = sDevicePropertiesService.list(new LambdaQueryWrapper<SDeviceProperties>().eq(SDeviceProperties::getEquipmentType, equipmentType));
        result.put("construction",list);
        //附加属性值
        List<SDeviceAddProperties> addList = deviceAddPropertiesService.list(new LambdaQueryWrapper<SDeviceAddProperties>().eq(SDeviceAddProperties::getEquipmentIdKey, equipmentIdKey));
        result.put("addProperties",addList);
        return AjaxResult.success(result);
    }

    /**
     * 查询设备列表
     */
    @GetMapping("/dictList")
    @ApiOperation(value="查询设备列表", notes="查询设备列表")
    public AjaxResult dictList()
    {
        QueryWrapper<SEquipment> wrapper = new QueryWrapper();
        //通过部门ID获取同部门的所有员工
        List<String> userList = iSysUserService.selectUserByDept(SecurityUtils.getLoginUser().getUser().getDeptId());
        Set<String> userByRoleSet = ParseSql.getUserByRoleUtil(userList);
        if (userByRoleSet != null && userByRoleSet.size() > 0){
            wrapper.in("create_by",userByRoleSet);
        }
        List<SEquipment> list = sEquipmentService.list(wrapper);
        List<Map> mapList = new ArrayList<>();
        list.stream().forEach(l ->{
            Map<String,Object> map = new HashMap();
            map.put("dictValue", l.getId());
            map.put("dictLabel",l.getEquipmentId());
            mapList.add(map);
        });
        return AjaxResult.success(mapList);
    }

    /**
     * 导出设备列表
     */
    @PreAuthorize("@ss.hasPermi('system:equipment:export')")
    @Log(title = "设备", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ApiOperation(value="导出设备列表", notes="导出设备列表")
    public AjaxResult export(@ApiParam SEquipment sEquipment)
    {
        QueryWrapper<SEquipment> wrapper = new QueryWrapper();
        //通过部门ID获取同部门的所有员工
        List<String> userList = iSysUserService.selectUserByDept(SecurityUtils.getLoginUser().getUser().getDeptId());
        Set<String> userByRoleSet = ParseSql.getUserByRoleUtil(userList);
        if (userByRoleSet != null && userByRoleSet.size() > 0){
            wrapper.in("create_by",userByRoleSet);
        }
        List<SEquipment> list = parse(sEquipmentService.list(wrapper));
        ExcelUtil<SEquipment> util = new ExcelUtil<SEquipment>(SEquipment.class);
        return util.exportExcel(list, "equipment");
    }

    /**
     * 导出数据转换
     * @param list
     * @return
     */
    private List<SEquipment> parse(List<SEquipment> list){
        list.stream().forEach(l -> {
            l.setMachineCabinet(sMachineCabinetService.getById(l.getMachineCabinet()).getMachineCabinetName());
            l.setEquipmentType(DictUtils.getDictLabel("equipment_type",l.getEquipmentType()));
            l.setRunningStatus(DictUtils.getDictLabel("running_status",l.getRunningStatus()));
        });
        return list;
    }
    /**
     * 获取设备详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:equipment:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value="获取设备详细信息", notes="获取设备详细信息")
    public AjaxResult getInfo(@ApiParam @PathVariable("id") String id)
    {
        return AjaxResult.success(sEquipmentService.getById(id));
    }

    /**
     * 新增设备
     */
    @PreAuthorize("@ss.hasPermi('system:equipment:add')")
    @Log(title = "设备", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value="新增设备", notes="新增设备")
    public AjaxResult add(@ApiParam @RequestBody SEquipment sEquipment)
    {
        sEquipment.setCreateBy(SecurityUtils.getUsername());
        int result = sEquipmentService.save(sEquipment) == true ? 1 : 0;
        return toAjax(result);
    }

    @PreAuthorize("@ss.hasPermi('system:equipment:saveOrUpdate')")
    @Transactional
    @Log(title = "设备", businessType = BusinessType.INSERT)
    @ApiOperation(value="新增或修改设备", notes="新增或修改设备")
    @PostMapping("/saveOrUpdate")
    public AjaxResult saveOrUpdate(@ApiParam @RequestBody Map map)
    {
        Map sEquipmentMap = (Map) map.get("sEquipment");
        List<Map> addProp = (List<Map>) map.get("addProp");
        SEquipment sEquipment = BeanUtil.toBean(sEquipmentMap, SEquipment.class);//设备ID
        sEquipment.setCreateBy(SecurityUtils.getUsername());
        if(sEquipment.getId() != null ){//如果ID不为空，则是修改操作
            SEquipment byId = sEquipmentService.getById(sEquipment.getId());
            sEquipment.setCreateTime(byId.getCreateTime());
        }else{
            sEquipment.setCreateTime(DateUtil.date());
        }
        sEquipmentService.saveOrUpdate(sEquipment);
        List<SDeviceAddProperties> list = new ArrayList();
        deviceAddPropertiesService.remove(new LambdaQueryWrapper<SDeviceAddProperties>().eq(SDeviceAddProperties::getEquipmentIdKey, sEquipment.getEquipmentId()));
        addProp.stream().forEach(addp ->{
            SDeviceAddProperties deviceAddProperties = BeanUtil.toBean(addp, SDeviceAddProperties.class);
            deviceAddProperties.setCreateBy(SecurityUtils.getUsername());
            deviceAddProperties.setCreateTime(DateUtil.date());
            deviceAddProperties.setEquipmentIdKey(sEquipment.getEquipmentId());
            list.add(deviceAddProperties);
        });
        deviceAddPropertiesService.saveOrUpdateBatch(list);
        return AjaxResult.success("保存成功");
    }

    /**
     * 修改设备
     */
    @PreAuthorize("@ss.hasPermi('system:equipment:edit')")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value="修改设备", notes="修改设备")
    public AjaxResult edit(@ApiParam @RequestBody SEquipment sEquipment)
    {
        int result = sEquipmentService.updateById(sEquipment) == true ? 1 : 0;
        return toAjax(result);
    }

    /**
     * 删除设备
     */
    @PreAuthorize("@ss.hasPermi('system:equipment:remove')")
    @Log(title = "设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value="删除设备", notes="删除设备")
    public AjaxResult remove(@ApiParam @PathVariable String[] ids)
    {
        List<String> list = Arrays.asList(ids);
        int result = sEquipmentService.removeByIds(list) == true ? 1 : 0;
        return toAjax(result);
    }

    /**
     * 导出设备模板
     * @return
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        return AjaxResult.success("DLBDZ_设备.xls");
    }

    @Log(title = "导入设备管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:equipment:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file)
    {
        String message = sEquipmentService.importsSEquipment(file);
        return AjaxResult.success(message);
    }

}
